package com.reason.pay.controller;

import com.alibaba.fastjson.JSON;
import com.reason.common.utils.IdWorker;
import com.reason.order.feign.OrderFeign;
import com.reason.order.pojo.Order;
import com.reason.pay.config.RabbitMqConfig;
import com.reason.pay.config.TokenDecode;
import com.reason.pay.service.WXPayService;
import com.github.wxpay.sdk.WXPayUtil;
import com.reason.common.pojo.Result;
import com.reason.common.pojo.StatusCode;
import com.reason.common.utils.ConvertUtils;
import com.reason.user.feign.CustomerFeign;
import com.reason.user.pojo.Customer;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

/**
 * @author 陈正果
 * @date 2020/06/30 1:03
 */
@Controller
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private WXPayService wxPayService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TokenDecode tokenDecode;

    @Autowired
    private CustomerFeign customerFeign;

    @Autowired
    private OrderFeign orderFeign;

    /**
     * 微信支付下单
     *
     * @return Result
     */
    @RequestMapping("/wxpay/member")
    public String wxpay(@RequestParam Integer money, Model model,HttpServletResponse response, HttpServletRequest request) {
        long id = idWorker.nextId();
        String orderId = id + "";

        String payMoney = "0.01";
        Map<String, String> resultMap = wxPayService.nativePay(orderId, payMoney);

        Order order = new Order();
        //设置订单id
        order.setId(orderId);
        //设置订单创建时间
        order.setCreateTime(new Date());
        //设置订单更新时间
        order.setUpdateTime(new Date());
        //通过token获取用户姓名
//        Map<String, String> userInfo = tokenDecode.getUserInfo();
//        String username = userInfo.get("username");
        String username = getCookie("username", request);
        order.setUsername(username);
        //调用feign接口查询用户id
//        Long userId = customerFeign.findbyName(username).getId();
        order.setUserId(getCookie("id", request));
        //设置订单状态
        order.setOrderStatus("0");
        //设置订单支付状态
        order.setPayStatus("0");

        //将订单信息通过mq传递到订单创建队列
        rabbitTemplate.convertAndSend(RabbitMqConfig.EX_ORDER_CREATE, "", JSON.toJSONString(order));

        //将二维码信息传递到前端
        model.addAttribute("code_url", resultMap.get("code_url"));
        model.addAttribute("money", money);

        response.setHeader("X-Frame-Options", "SAMEORIGIN");

        return "paydetail";
    }

    /**
     * 微信支付成功回调接口
     *
     * @param request  请求
     * @param response 响应
     */
    @RequestMapping("/notify")
    public void wxpayNotify(HttpServletRequest request, HttpServletResponse response) {
        try {
            //获取微信返回流
            String xml = ConvertUtils.convertToString(request.getInputStream());
            Map<String, String> map = WXPayUtil.xmlToMap(xml);

            //如果支付成功
            if (map.get("result_code").equals("SUCCESS")) {
                //获取orderId
                String orderId = map.get("out_trade_no");

                //查询订单结果
                Map<String, String> resultMap = wxPayService.queryOrder(orderId);

                if (resultMap.get("result_code").equals("SUCCESS")) {
                    //如果支付成功,封裝order信息，通过mq传递订单信息
                    Order order = new Order();
                    order.setId(resultMap.get("out_trade_no"));

                    order.setPayMoney(Long.parseLong(resultMap.get("total_fee")));
                    order.setTotalMoney(Long.parseLong(resultMap.get("total_fee")));
                    order.setUpdateTime(new Date());
                    order.setEndTime(new Date());
                    order.setCloseTime(new Date());

                    String transaction_id = resultMap.get("transaction_id");
                    order.setTransactionId(transaction_id);

                    order.setOrderStatus("1");
                    order.setPayStatus("1");

                    Order out_trade_no = orderFeign.findById(resultMap.get("out_trade_no"));
                    order.setUserId(out_trade_no.getUserId());

                    rabbitTemplate.convertAndSend(RabbitMqConfig.EX_ORDER_SUCCESS, "", JSON.toJSONString(order));

                } else {
                    System.out.println(resultMap.get("err_code_des"));
                }
            }

            //通知微信成功收到消息
            response.setContentType("text/xml");
            String data = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg" +
                    "></xml>";
            response.getWriter().write(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getCookie(String name, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length == 0) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(name)) {
                return cookie.getValue();
            }
        }
        return null;
    }

}
